package com.atguigu.tingshu.payment.strategy;

import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.user.UserInfo;
import com.atguigu.tingshu.payment.config.WxPayV3Config;
import com.atguigu.tingshu.user.client.UserInfoFeignClient;
import com.atguigu.tingshu.vo.payment.WeChatPayVo;
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;

public interface WeChatPayStrategy {

    // 请求微信支付jsapi下单接口的抽象方法
    public abstract WeChatPayVo createJsapi(String paymentType, String orderNo);

    // 获取支付类型的抽象方法
    public abstract String getPaymentType();

    public default WeChatPayVo wxCreateJsapi(UserInfoFeignClient userInfoFeignClient ,
                                             RSAAutoCertificateConfig rsaAutoCertificateConfig,
                                             WxPayV3Config wxPayV3Config , String description , String orderNo , Integer money) {

        // 获取当前登录用户的id
        Long userId = AuthContextHolder.getUserId();
        Result<UserInfo> userInfoResult = userInfoFeignClient.getUserInfoById(userId);
        UserInfo userInfo = userInfoResult.getData();

        // 请求微信支付平台的jsapi的下单接口
        JsapiServiceExtension jsapiServiceExtension = new JsapiServiceExtension.Builder().config(rsaAutoCertificateConfig).build();

        // 创建PrepayRequest对象，封装请求参数
        PrepayRequest prepayRequest = new PrepayRequest() ;
        prepayRequest.setAppid(wxPayV3Config.getAppid());
        prepayRequest.setMchid(wxPayV3Config.getMerchantId());
        prepayRequest.setDescription(description);
        prepayRequest.setOutTradeNo(orderNo);
        prepayRequest.setNotifyUrl(wxPayV3Config.getNotifyUrl());       // 异步通知的url

        Amount amount = new Amount();
        // amount.setTotal(orderInfo.getOrderAmount().multiply(new BigDecimal("100")).intValue() );
        amount.setTotal(money);
        prepayRequest.setAmount(amount);

        Payer payer = new Payer();
        payer.setOpenid(userInfo.getWxOpenId());
        prepayRequest.setPayer(payer);
        PrepayWithRequestPaymentResponse response = jsapiServiceExtension.prepayWithRequestPayment(prepayRequest);

        // 构建响应结果数据
        WeChatPayVo weChatPayVo = new WeChatPayVo() ;
        weChatPayVo.setTimeStamp(response.getTimeStamp());
        weChatPayVo.setNonceStr(response.getNonceStr());
        weChatPayVo.setPackageVal(response.getPackageVal());
        weChatPayVo.setSignType(response.getSignType());
        weChatPayVo.setPaySign(response.getPaySign());

        return weChatPayVo ;

    }
}
